class Dep {
  constructor() {
    this.subscribers = new Set() 

  }
  // addEffect(effect) {
  //   this.subscribers.add(effect)
  // }
  notify() {
    this.subscribers.forEach(effect => {
      effect()
    })
  }
  depend() {
    if (activeEffect) {
      this.subscribers.add(activeEffect)
    }
  }
}

let activeEffect = null

function watchEffect(effect) {
  //  dep.addEffect(effect)
  activeEffect = effect
  effect()
  activeEffect = null 
}

// Map({key: value}): key是一个字符串
// WeakMap({key(对象):value}): key是一个对象, 弱引用


const targetMap = new WeakMap()

function getDep(target, key) {
  // 1.根据对象那(target)取出对应的Map对象
  let depsMap = targetMap.get(target)
  if (!depsMap) {
    depsMap = new Map()
    targetMap.set(target, depsMap)
  }
  // 2.取出具体的dep对象
  let dep = depsMap.get(key)
  if (!dep) {
    dep = new Dep()
    depsMap.set(key, dep)
  }
  return dep
}



// vue3对raw进行数据劫持
function reactive(raw) {
  return new Proxy(raw, {
    get(target, key) {
      const dep = getDep(target, key)
      dep.depend()
      return Reflect.get(target, key)
    },
    set(target, key, newValue) {
      const dep = getDep(target, key)
      const result = Reflect.set(target, key, newValue)
      dep.notify()
      return result
    },
    deleteProperty(target, key) {
      const dep = getDep(target, key)
     const result = Reflect.deleteProperty(target, key)
      dep.notify()
      return result
    }
  })
}


const info = reactive({ counter: 100, name: 'yanzhi' })

const foo = reactive({ height: 1.88 })

const dep = new Dep()

// watchEffect1
watchEffect(function () {
  console.log('effect1',info.counter * 2, info.name);
})


// watchEffect2
watchEffect(function () {
  console.log('effect2',info.counter * info.counter);
})

// watchEffect3
watchEffect(function () {
  console.log('effect3',info.counter + 10, info.name);
})

watchEffect(function () {
  console.log('effect4',foo.height);
})

// info.counter++
info.name = '111'
